package com.atxyj.prototype.mode;


import java.util.HashMap;
import java.util.Scanner;

interface Shape extends Cloneable{

  public Object clone();

  public void countArea();
}

class Circle implements Shape {

    @Override
    public Object clone() {
        Circle circle = null;
        try {
            circle = (Circle) super.clone();
        } catch (Exception e) {
            System.out.println("拷贝圆失败");
        }
        return circle;
    }

    @Override
    public void countArea() {
        int r = 0;
        System.out.println("这是一个圆，请输入圆的半径：");
        Scanner input = new Scanner(System.in);
        r = input.nextInt();
        System.out.println("该圆的面积=" + 3.1415 * r * r + "\n");
    }
}
 class Square implements Shape {

     @Override
     public Object clone() {
         Square square = null;
         try {
             square = (Square) super.clone();
         } catch (Exception e) {
             System.out.println("拷贝圆失败");
         }
         return square;
     }

     @Override
     public void countArea() {
         int a = 0;
         System.out.println("这是一个正方形，请输入它的长度：");
         Scanner input = new Scanner(System.in);
         a = input.nextInt();
         System.out.println("该正方形的面积=" + a * a + "\n");
     }
 }

/**
 * 原型模式的应用实例：【例3】用带原型管理器的原型模式来生成包含“圆”和“正方形”等图形的原型，并计算其面积。
 */
public class ProtoTypeManagerDemo {
    private HashMap<String,Shape> ht = new HashMap<>();

    public ProtoTypeManagerDemo() {
        ht.put("Circle", new Circle());
        ht.put("Square", new Square());
    }

    public void addShape(String key,Shape value) {
        ht.put(key,value);
    }

    public Shape getShape(String key ) {
        Shape temp = ht.get(key);
        return (Shape)temp.clone();
    }



}

 class ProtoTypeShape{
     public static void main(String[] args) {
         ProtoTypeManagerDemo pm = new ProtoTypeManagerDemo();
         Shape shape1 = (Circle)pm.getShape("Circle");
         shape1.countArea();
         Shape shape2 = (Square)pm.getShape("Square");
         shape2.countArea();
     }

}